package admin.controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import entities.Category;

import admin.forms.CategoryForm;
import admin.models.CategoryModel;

public class CategoryAddServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {

		TreeMap<String, String> check = new TreeMap<String, String>();
		
		Category category = new Category();
		category.setId(IdUniqueHelper.getId());
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("category", category);
		try {
			request.getRequestDispatcher("/admin/pages/category_form.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		Category category = new Category();
		
		TreeMap<String, Object> form = (TreeMap<String, Object>) CategoryForm.checkValid(request, category);
		category = (Category) form.get("category");
		check = (TreeMap<String, String>) form.get("checkValid");
		
		if (check.size() == 0) {
			categoryModel.insert(category);

			request.setAttribute("success", "Add success category " + category.getName());
			category = new Category();
			category.setId(IdUniqueHelper.getId());
		}
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("category", category);
		try {
			request.getRequestDispatcher("/admin/pages/category_form.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
